package com.example.admin.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    // 处理特定异常，如验证异常
//    @ExceptionHandler(MethodArgumentNotValidException.class)
//    public ResponseEntity<Map<String, Object>> handleValidationException(MethodArgumentNotValidException ex) {
//        Map<String, Object> response = new HashMap<>();
//        Map<String, String> errors = new HashMap<>();
//
//        // 提取验证错误信息
//        ex.getBindingResult().getAllErrors().forEach((error) -> {
//            String fieldName = ((FieldError) error).getField();
//            String errorMessage = error.getDefaultMessage();
//            errors.put(fieldName, errorMessage);
//        });
//
//        // 构建响应体
//        response.put("status", HttpStatus.BAD_REQUEST.value());
//        response.put("error", "Validation Failed");
//        response.put("message", "Input validation failed for the request");
//
//        return new ResponseEntity<>(response, HttpStatus.OK);
//    }

    @ExceptionHandler(AdminException.class)
    public ResponseEntity<Map<String, Object>> handleAdminException(AdminException ex, WebRequest request) {
        Map<String, Object> response = new HashMap<>();
        response.put("code", ex.getErrorCode());
        response.put("status", 0);
        response.put("msg", ex.getMessage());

        return new ResponseEntity<>(response, HttpStatus.OK);
    }

    // 处理通用异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<Map<String, Object>> handleGlobalException(Exception ex, WebRequest request) {
        Map<String, Object> response = new HashMap<>();

        // 获取异常的堆栈跟踪
        StackTraceElement[] stackTraceElements = ex.getStackTrace();
        String[] stackTraceArray = new String[stackTraceElements.length];
        for (int i = 0; i < stackTraceElements.length; i++) {
            stackTraceArray[i] = stackTraceElements[i].toString();
        }

        // 记录异常信息
        logger.error("Exception occurred: " + ex.getMessage());
        logger.error("Stack trace: ");
        for (String trace : stackTraceArray) {
            logger.error(trace);
        }

        response.put("code", 500);
        response.put("status", 0);
        response.put("msg", ex.getMessage());
        response.put("stack", stackTraceArray);

        return new ResponseEntity<>(response, HttpStatus.OK);
    }

}


